<?php
/**
 * Created by lzl
 * Date: 2021 2021/8/31
 * Time: 15:12
 */
namespace App\Forms;

use App\Models\Admin;
use App\Models\AdminGroup;
use App\Models\GroupMenuRelation;
use App\Models\Menu;

class RbacForms extends BaseForm
{

    /**
     * @return mixed
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public static function getAdminMenu()
    {
        $res = \Cache::get(auth('admin')->id().'_menu');

        if(blank($res)){
            $res = self::setAdminMenu();
        }

        return $res;
    }


    /**
     * @return \Illuminate\Support\Collection
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public static function setAdminMenu()
    {
        $menuList = GroupMenuRelation::where('gid', auth('admin')->user()->gid)->get(['menu_id'])->toArray();

        //todo 仅适用两层菜单结构，懒得写无限极分类了
        $menu = Collect(Menu::where('pid',0)
            ->whereIn('id', $menuList)
            ->orderBy('sort','desc')
            ->orderBy('id','asc')
            ->get()
            ->toArray())
            ->map(function ($res) use ($menuList){
                 $res['children'] = Menu::where('pid', $res['id'])
                         ->whereIn('id', $menuList)
                         ->orderBy('sort','desc')
                         ->orderBy('id','asc')
                         ->get()
                         ->toArray() ?? [];
                 return $res;
            });

        \Cache::set(auth('admin')->id().'_menu', $menu);

        return $menu;
    }


    /**
     * @param Admin $admin
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function refreshAdminMenu(Admin $admin)
    {
        if(\Cache::pull($admin->id.'_menu')){
            self::setAdminMenu();
        }
    }


    /**
     * @param $validated
     * @return array
     */
    public function getManagerGroup($validated)
    {
        $groupMenu = GroupMenuRelation::where('gid', $validated['id'] ?: 0 )
                ->pluck('menu_id')->toArray() ?? [];

        $field = ['id', 'pid', 'name as title'];
        //TODO 两级菜单写法 多级需要调整
        $menu = Collect(Menu::where('pid',0)
            ->orderBy('sort','desc')
            ->orderBy('id','asc')
            ->get($field)
            ->toArray())
            ->map(function ($res) use($field) {
                $res['children'] = Menu::where('pid', $res['id'])
                        ->orderBy('sort','desc')
                        ->orderBy('id','asc')
                        ->get($field)
                        ->toArray() ?? [];
                return $res;
            })->toArray();

        foreach ($menu as &$v){
            $v['checked'] = (boolean)in_array($v['id'], $groupMenu);
            if(count($v['children'])){
                unset($v['checked']);

                foreach ($v['children'] as &$item2){
                    $item2['checked'] =  (boolean)in_array($item2['id'], $groupMenu);
                }
            }
        }

        return compact('menu');
    }


    /**
     * 修改权限组
     * @param $validated
     * @return bool
     */
    public function editManagerGroup($validated)
    {

        $group = AdminGroup::updateOrCreate(['id' => $validated['id'] ?? 0 ], $validated);

        if(is_array($validated['menu_id'])){
            //先删除，后添加
            GroupMenuRelation::where('gid', $group->id)->delete();

            foreach ($validated['menu_id'] as $item) {
                GroupMenuRelation::create([
                    'gid'     => $group->id,
                    'menu_id' => $item['id']
                ]);
                if(isset($item['children']) && is_array($item['children'])){
                    foreach ($item['children'] as $item2){
                        GroupMenuRelation::create([
                            'gid'     => $group->id,
                            'menu_id' => $item2['id']
                        ]);
                    }
                }
            }
        }

        return true;
    }

}